package com.rn.ddd.infrastructure.engine;

import com.rn.ddd.infrastructure.engine.constant.OrderStateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 抽象状态处理器抽象
 *
 * @author 然诺
 * @date 2022/3/5
 */
@Slf4j
@Component
public abstract class AbstractStateProcessor<T, E> implements StateProcessor<T, E>, StateActionStep<T, E> {

    @Autowired
    private PluginExecutor pluginExecutor;

    @Override
    public Result<T> execute(StateContext<E> context) throws Exception {
        Result<T> result;
        try {
            // 1.准备
            prepare(context);
            // 2.校验
            result = check(context);
            if (!result.isSuccess()) {
                log.info("check fail....................");
                return result;
            }
            // 3.获取下一个状态
            OrderStateEnum nextState = getNextState(context);
            if (nextState == null) {
                log.info("getNextState fail....................");
                return null;
            }
            // 4.执行业务操作
            result = operate(context, nextState);
            if (!result.isSuccess()) {
                log.info("operate fail....................");
                return result;
            }
            // 在action和save之间执行插件逻辑
            pluginExecutor.parallelExecutor(getPlugins(context), context);
            // 5.持久化
            result = persistence(context, nextState);
            if (!result.isSuccess()) {
                log.info("persistence fail....................");
                return result;
            }
            // 6.后处理
            result = after(context);
            if (!result.isSuccess()) {
                log.info("after fail....................");
                return result;
            }
        } catch (Exception e) {
            log.error("execute error", e);
            throw e;
        }
        return result;
    }

}
